package com.project.fortuneteller.config;

import com.project.fortuneteller.controller.intecepter.GlobalAuthIntecepter;
import com.project.fortuneteller.websocketHandler.WebSocketInterceptor;
import com.project.fortuneteller.websocketHandler.WsHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.annotation.Resource;



@Slf4j  // @EnableWebMvc 注释掉也没用
@Configuration
@EnableWebSocket
public class WebMvcConfig extends WebMvcConfigurationSupport implements WebSocketConfigurer {

   @Resource
    WsHandler wsHandler ;

   @Resource
   WebSocketInterceptor webSocketInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 1. 映射 /resources/** 到类路径下的 /resources/ 目录
        String type = System.getProperty("os.name");
        // 判断操作系统的类型
        if(type.toLowerCase().contains("win")){
            // files
            registry.addResourceHandler("/files/**").addResourceLocations("file:\\files");
        }else{
            registry.addResourceHandler("/files/**").addResourceLocations("file:/files");
        }

        // 有效的URL 为
        // http://localhost:8089/api/uploadPath/2025-10-11/c6aafba5-9146-40ef-b763-bbec435d3f80.jpg
    }


    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new GlobalAuthIntecepter()).addPathPatterns("/**")
                .excludePathPatterns("/login","/register","/files/files/**","/loginFace","/uploadImg","/uploadImg/face");
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
         // 添加路由
        registry.addHandler(wsHandler,"/myWs1").addInterceptors(webSocketInterceptor)
                .setAllowedOrigins("*");
    }
}
